<?php

namespace App\Library\Service;

use App\Library\Traits\BaseServiceTrait;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;

class BaseService
{
    use BaseServiceTrait;

    /**
     * baseLoginByCode
     * @param string $code
     * @param string $type
     * @return Model|JsonResponse
     * @throws GuzzleException
     */
    protected function baseLoginByCode(string $code, string $type): JsonResponse|array
    {
        $es = esCache();
        $lWechat = __('wechat');
        $appName = config('app.name');
        $key = Arr::get($es, implode('.', [$type, 'key']));
        $secret = Arr::get($es, implode('.', [$type, 'secret']));
        if ($type === 'mp') $url = sprintf(Arr::get($lWechat, implode('.', ['wx', 'url', 'step2'])), $key, $secret, $code);
        else $url = sprintf(Arr::get($lWechat, implode('.', ['mini', 'url'])), $key, $secret, $code);
        $client = new Client;
        $data = json_decode($client->get($url)->getBody()->getContents(), true);
        if (!empty($data['errcode'])) return failMessage($data['errmsg']);
        else if (empty($data['unionid'])) return fail(499);
        return $data;
    }
}
